import { createRouter, createWebHistory } from 'vue-router'
import { useStore } from '@/stores'
import { routes } from '@/config'

/** 路由配置 */
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: <any>routes
})

// 全局路由守卫
router.beforeEach((to, from, next) => {
  // console.log("从哪来", from);
  // console.log("到哪去", to);

  /** 判断路由跳转时是否登录 */
  if (
    (from.name === undefined && to.name === 'Login') ||
    (from.name === 'Login' && to.name === 'Home')
  ) {
    //
  } else {
    // if (!useStore().GBToken) {
    //   useStore().GBReturnLogin = ''
    //   router.replace({ name: 'Login' }).then()
    //   return
    // }
    useStore().PageTabsOpen(to)
  }

  /** 处理路由中带有 params 参数的事件 */
  if (JSON.stringify(to.params) !== '{}' && from.name !== undefined) {
    const path = to.fullPath
    const match = path.match(/(\/.*\/)/)
    if (match) {
      to.fullPath = match[0]
    }
  } else if (JSON.stringify(to.params) !== '{}' && from.name === undefined) {
    /** 清空刷新页面后 路由残留的参数 */
    to.params = {}
  }

  next()
})

export default router
